<template>
  <div class="gt-box">
    <div @click="validate">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      captchaObj: null
    };
  },
  async mounted() {
    let { data } = await this.$http.get("/api/gt/register-click");
    initGeetest(
      {
        // 以下 4 个配置参数为必须，不能缺少
        gt: data.gt,
        challenge: data.challenge,
        offline: !data.success, // 表示用户后台检测极验服务器是否宕机
        new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机

        product: "bind", // 产品形式，包括：float，popup
        width: "300px"

        // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
      },
      captchaObj => {
        this.captchaObj = captchaObj;
        captchaObj.onSuccess(() => {
          var result = captchaObj.getValidate();
          this.$http
            .post("/api/gt/validate-click", {
              ...result
            })
            .then(resp => {
              console.log(resp);
              this.$emit("smsCodeSucess", resp.data.result);
            });
        });
      }
    );
  },
  methods: {
    validate() {
      if (this.captchaObj) {
        this.captchaObj.verify();
      }
    }
  },
  beforeDestroy() {
    if (this.captchaObj) {
      this.captchaObj = null;
      Array.prototype.slice
        .call(document.querySelectorAll(".geetest_panel"))
        .forEach(element => {
          document.body.removeChild(element);
        });
    }
  }
};
</script>
